package net.csiit.tools.fileserver.core.storage;

import net.csiit.tools.fileserver.common.util.DateUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author adam
 * @date 2020-11-17
 */
@Service
public class LocalFileStorageImpl implements FileStorage {

    @Value("${file.storage.basedir}")
    private String baseDir;

    /**
     * 返回文件路径
     * @param file
     * @return
     * @throws IOException
     */
    @Override
    public String saveFile(File file) throws IOException {
        try (InputStream inputStream = new FileInputStream(file)) {
            return this.saveFile(inputStream, getFileType(file.getName()));
        }
    }

    /**
     * 返回文件路径
     * @param inputStream 输入流, 调用方需要关闭此输入流
     * @param fileType 文件类型  后缀名  即 doc  docx  jpg 等
     * @return
     * @throws IOException
     */
    @Override
    public String saveFile(InputStream inputStream, String fileType) throws IOException {
        String newFileName = System.currentTimeMillis() + RandomStringUtils.randomNumeric(6);
        if (!StringUtils.isEmpty(fileType)) {
            newFileName = newFileName + "." + fileType;
        }

        String filePath = getMonth() + File.separator + newFileName;
        File dest = new File(baseDir, filePath);
        this.ensureDirectory(dest);

        try (OutputStream outputStream = new FileOutputStream(dest)) {
            IOUtils.copy(inputStream, outputStream);
        }

        return filePath;
    }

    @Override
    public InputStream readFile(String fileId) throws FileNotFoundException {
        return new FileInputStream(new File(baseDir, fileId));
    }

    @Override
    public boolean deleteFile(String fileId) {
        File file = new File(baseDir, fileId);
        if (file.exists()) {
            return file.delete();
        }

        return false;
    }

    private String getMonth() {
        return DateUtil.getCurrentMonth();
    }

    private String getMonthFk() {
        return new SimpleDateFormat("yyyy-MM").format(new Date());
    }

    private void ensureDirectory(File file) {
        File dir = file.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    private String getFileType(String fileName) {
        int idx = fileName.lastIndexOf(".");
        if (idx == -1) {
            return null;
        }

        return fileName.substring(idx + 1);
    }
}
